import React, { useEffect, useState } from "react";
import { View, Text, Image } from "@tarojs/components";
import "./index.scss";
import { NoDataProps, NoDataPreset } from "../../../types/components/no-data";

const common = {
  no_data: "https://cdn.yryz.com/lovelorn/image/fatelove/empty/no_data1_4.png",
  no_search:
    "https://cdn.yryz.com/lovelorn/image/fatelove/empty/no_search1_4.png",
  no_loverank:
    "https://cdn.yryz.com/lovelorn/image/fatelove/empty/no-loverank@2x1_4.png",
  no_love:
    "https://cdn.yryz.com/lovelorn/image/fatelove/empty/no_love@2x1_4.png",
  noAccountDetail:
    "https://cdn.yryz.com/lovelorn/image/fatelove/empty/no-account-detail1_4.png",
  buy_recod:
    "https://cdn.yryz.com/lovelorn/image/fatelove/common/buy_recod1_4.png"
};

const presets: { [key: string]: NoDataPreset } = {
  "no-data": {
    image: common.no_data,
    content: "暂无相关数据"
  },
  "no-search": {
    image: common.no_search,
    content: "暂无任何搜索记录～"
  },
  "no-loverank": {
    image: common.no_loverank,
    content: "暂无任何排行信息"
  },
  "no-love": {
    image: common.no_love,
    content: "暂无任何排行信息"
  },
  "no-detail-money": {
    image: common.noAccountDetail,
    content: "暂无收支记录～"
  },
  "buy-recod": {
    image: common.buy_recod,
    content: "暂无任何邀请记录～"
  }
};

const Message: React.FC<NoDataProps> = ({
  className,
  image,
  preset,
  title,
  content,
  actionTitle,
  onAction
}) => {
  const [config, setConfig] = useState({} as any);

  const handleAction = () => {
    if (!onAction) {
      throw new Error("`onAction` is required if there is an action button.");
    }

    onAction();
  };

  useEffect(() => {
    if (preset) {
      setConfig({
        ...presets[preset],
        ...(title ? { title: title } : {}),
        ...(content ? { content: content } : {}),
        ...(actionTitle ? { actionTitle: actionTitle } : {})
      });
    } else {
      setConfig({
        image: image,
        title: title,
        content: content,
        actionTitle: actionTitle
      });
    }
  }, [preset, image, title, content, actionTitle]);

  const renderImage = () => {
    return config.image ? <Image src={config.image} className="image" /> : null;
  };
  const renderTitle = () => {
    return config.title ? <Text className="title">{config.title}</Text> : null;
  };

  const renderContent = () => {
    return config.content ? (
      <Text className="content">{config.content}</Text>
    ) : null;
  };

  const actionButton = () => {
    return actionTitle ? (
      <View onClick={handleAction} className="actionButton">
        <Text className="actionTitle">{actionTitle}</Text>
      </View>
    ) : null;
  };

  return (
    <View className={`message-main ${className}`}>
      {renderImage()}
      {renderTitle()}
      {renderContent()}
      {actionButton()}
    </View>
  );
};

export default Message;
